package main
import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
)
// 告警消息
type AppAlertMsg struct{
	//警告状态 down/up
	Status string `json:"status"`
	// app描述
	Desc string `json:"desc"`
	// 监控url接口
	AppUrl string `json:"url"`
	// 告警时间
	AlertTime string `json:"alerttime"`
}

// 企业微信发送textcart类型消息
func sendTextCardMsg(msg AppAlertMsg, token string) (err error){
	url := fmt.Sprintf("%s?access_token=%s", configMap["qywechat"]["sendmsgurl"], token)
	agentid, _ := strconv.ParseInt(configMap["qywechat"]["agentid"], 10, 64)
	contentType := "application/json"
	data := fmt.Sprintf(
		`{
			"touser" : "%s",
			"msgtype" : "textcard",
			"agentid" : %d,
			"textcard" : {
					 "title" : "App报警",
					 "description" : "<div class=\"highlight\">%s</div> <div class=\"normal\">%s</div> <div class=\"normal\">%s</div> <div class=\"gray\">%s</div>",
					 "url" : "%s",
					 "btntxt":"查看"
			}
		 }`,
		processToUser(configMap["qywechat"]["touser"]),
		agentid,
		msg.Status,msg.Desc,msg.AppUrl,msg.AlertTime,msg.AppUrl)

	resp, err := http.Post(url, contentType, strings.NewReader(data))
	if err != nil {
		fmt.Printf("post failed, err:%v\n", err)
		return
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("get resp failed, err:%v\n", err)
		return
	}

	var resVal map[string]interface{}
	_ = json.Unmarshal(b, &resVal)
	resCode, _ := resVal["errcode"].(int64)
	if resCode != 0 {
		err = fmt.Errorf("发送消息失败, 返回结果: %s", string(b))
		return
	}
	return
}


//app应用监控报警接口，触发企业微信发送textcard消息
func appMonitorHandler(w http.ResponseWriter, r *http.Request){
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	// fmt.Println(string(body))
	var msg AppAlertMsg
	if err := json.Unmarshal(body, &msg);err != nil {
        fmt.Printf("Unmarshal err, %v\n", err)
        return
    }
	// fmt.Println(msg.AppUrl)
	validToken(&accessToken)
	err = sendTextCardMsg(msg, accessToken.AccessToken)
	if err != nil {
		fmt.Println(err)
		fmt.Fprintf(w, "企业微信发送失败%v", err)
		return
	}
	// if configMap["globals"]["mysql"] == "on" {
	// 	for _, a := range alert {
	// 		err = insertRow(a, "企业微信")
	// 		if err != nil {
	// 			fmt.Println(err)
	// 			fmt.Fprintf(w, "邮件发送记录入库失败%v", err)
	// 			return
	// 		}
	// 	}
	// }
}